package com.rjj.wlqq.pdf;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

public class TemplateToPDFFreemarker extends BasePDF{
    private static Configuration freemarkerCfg = null;
    private static String path;
    static {
        freemarkerCfg =new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        try {
            path = ResourceUtils.getURL("classpath:templates/pdf/").getPath();
            //freemarker的模板目录，下边两个设置路径方式都可以
            freemarkerCfg.setDirectoryForTemplateLoading(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //path = "/templates/pdf";
        //freemarkerCfg.setClassForTemplateLoading(TemplateToPDFFreemarker.class,"/templates/pdf");
    }

    @Override
    public String templateToString(Map<String, Object> data, String htmlTmp) {
        Writer out = new StringWriter();
        try {
            // 获取模板,并设置编码方式
            Template template = freemarkerCfg.getTemplate(htmlTmp,"UTF-8");
            //template.setEncoding("UTF-8");
            // 合并数据模型与模板
            //将合并后的数据和模板写入到流中，这里使用的字符流
            template.process(data, out);
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return "";
    }
}
